package com.sgu6.sgu6_machine.ui.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.sgu6.middleware.event.MachineIdEvent;
import com.sgu6.netty.container.ChannelContainer;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.base.BaseA;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.dto.MachineLoginDto;
import com.sgu6.sgu6_machine.presenter.MachineP;
import com.sgu6.sgu6_machine.ui.MainA;
import com.sgu6.sgu6_machine.util.FileUtils;
import com.sgu6.sgu6_machine.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MachineIdA extends BaseA {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_machine_id)
    EditText etMachineId;
    @BindView(R.id.et_machine_pwd)
    EditText etMachinePwd;
    @BindView(R.id.progress)
    ProgressBar progressBar;

    MachineP machineP;
    String machineNo, machinePwd;
    AlertDialog.Builder dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_machine_id);
        ButterKnife.bind(this);

        initUI();

        initParams();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void initUI() {
        initToolbar();
        initDialog();
        etMachineId.setText(MachineContainer.machineConfigDto.machineNo);
    }

    public void initParams() {
        machineP = new MachineP();
    }

    private void initDialog() {
        dialog = new AlertDialog.Builder(this);
        dialog.setTitle("提示");
        dialog.setMessage("是否修改机器ID？");
        dialog.setNegativeButton("取消", (dialog, which) -> {
        });
        dialog.setPositiveButton("确定", (dialog, which) -> {
            machineP.login(machineNo, machinePwd);
            progressBar.setVisibility(View.VISIBLE);
        });
    }

    private void initToolbar() {
        toolbar.setTitle("机器id设置");
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setBackgroundResource(R.color.colorPrimaryDark);
        setSupportActionBar(toolbar);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return true;
    }

    @OnClick(R.id.btn_confirm)
    public void onViewClicked() {
        machineNo = etMachineId.getText().toString().trim();
        machinePwd = etMachinePwd.getText().toString().trim();
        if (machineNo.length() > 0 && machinePwd.length() > 0) {
            dialog.show();
        } else {
            ToastUtil.show(this, "请输入账号密码");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLogin(MachineLoginDto dto) {
        progressBar.setVisibility(View.GONE);
        if (dto.isSucceed()) {
            ToastUtil.show(MachineIdA.this, "机器id设置成功");
            EventBus.getDefault().post(new MachineIdEvent(true, machineNo));
            MachineContainer.machineConfigDto.machineNo = machineNo;
            MachineContainer.machineConfigDto.machinePassword = machinePwd;
            updateConfig();
            deleteLogo();
            restartApp();
        } else {
            ToastUtil.show(MachineIdA.this, dto.getErrMsg());
        }
    }

    public void restartApp() {
        ChannelContainer.CHANNEL.disconnect();
        ChannelContainer.CHANNEL.close();
        for (int i = 0; i < activities.size(); i++) {
            activities.get(i).finish();
        }
        Intent intent = new Intent(this, MainA.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

        android.os.Process.killProcess(android.os.Process.myPid());  //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
    }

    public void deleteLogo(){
        try {
            File file = FileUtils.getLocalImageByName("logo.png");
            if (file.exists()){
                file.delete();
            }
        }catch (Exception e){
            Log.i(TAG, "deleteLogo: "+e.getLocalizedMessage());
        }
    }

}
